import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { 
  ArrowLeft, Plus, Play, Pause, Trash2, 
  RefreshCw, Calendar, Clock,
  MoreHorizontal, Edit3, Copy, BarChart3
} from 'lucide-react'
import LoadingSpinner from '../components/LoadingSpinner'
import { apiRequest } from '../services/api'

interface RecurringTask {
  id: string
  title: string
  description?: string
  priority: string
  category: string
  tags: string[]
  notes?: string
  recurringType: 'daily' | 'weekly' | 'monthly' | 'yearly'
  recurringPattern: string | null
  isActive: boolean
  createdAt: string
  updatedAt: string
  instanceCount: number
  pendingCount: number
}

interface RecurringTaskStats {
  totalRecurringTasks: number
  activeRecurringTasks: number
  totalInstances: number
  upcomingInstances: number
}

export default function RecurringTasksPage() {
  const navigate = useNavigate()
  const [recurringTasks, setRecurringTasks] = useState<RecurringTask[]>([])
  const [stats, setStats] = useState<RecurringTaskStats | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [selectedTask, setSelectedTask] = useState<string | null>(null)

  useEffect(() => {
    loadRecurringTasks()
    loadStats()
  }, [])

  const loadRecurringTasks = async () => {
    try {
      setIsLoading(true)
      const tasks = await apiRequest<RecurringTask[]>('/recurring')
      // 确保每个任务都有必要的字段
      const tasksWithDefaults = tasks.map((task: any) => ({
        ...task,
        tags: task.tags || [],
        description: task.description || '',
        notes: task.notes || ''
      }))
      setRecurringTasks(tasksWithDefaults)
    } catch (error) {
      console.error('加载重复任务失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const loadStats = async () => {
    try {
      const statsData = await apiRequest<any>('/recurring/stats/overview')
      setStats(statsData)
    } catch (error) {
      console.error('加载统计数据失败:', error)
    }
  }

  const handleToggleActive = async (taskId: string, isActive: boolean) => {
    try {
      const endpoint = isActive ? 'pause' : 'resume'
      await apiRequest(`/recurring/${taskId}/${endpoint}`, {
        method: 'PATCH'
      })
      
      await loadRecurringTasks()
      await loadStats()
    } catch (error) {
      console.error('切换任务状态失败:', error)
    }
  }

  const handleGenerateInstances = async (taskId: string) => {
    try {
      const result = await apiRequest<{ count: number }>(`/recurring/${taskId}/generate`, {
        method: 'POST'
      })
      
      alert(`已生成 ${result.count} 个任务实例`)
      await loadRecurringTasks()
      await loadStats()
    } catch (error) {
      console.error('生成任务实例失败:', error)
    }
  }

  const handleCopyTask = (task: RecurringTask) => {
    // 导航到创建页面，并传递任务数据作为模板
    navigate('/create?recurring=true', {
      state: {
        template: {
          title: `${task.title} - 副本`,
          description: task.description,
          priority: task.priority,
          category: task.category,
          tags: task.tags,
          notes: task.notes,
          recurringType: task.recurringType,
          recurringPattern: task.recurringPattern
        }
      }
    })
  }

  const handleDeleteTask = async (taskId: string, title: string) => {
    if (confirm(`确定要删除重复任务"${title}"及其所有实例吗？`)) {
      try {
        await apiRequest(`/recurring/${taskId}`, {
          method: 'DELETE'
        })
        
        await loadRecurringTasks()
        await loadStats()
      } catch (error) {
        console.error('删除重复任务失败:', error)
      }
    }
  }

  const handleTriggerProcessing = async () => {
    try {
      await apiRequest('/recurring/trigger-processing', {
        method: 'POST'
      })
      
      alert('重复任务处理已触发')
      await loadRecurringTasks()
      await loadStats()
    } catch (error) {
      console.error('触发处理失败:', error)
    }
  }

  const getRecurringTypeLabel = (type: string) => {
    const labels = {
      daily: '每天',
      weekly: '每周',
      monthly: '每月',
      yearly: '每年'
    }
    return labels[type as keyof typeof labels] || type
  }

  const getRecurringPatternLabel = (pattern: string | null | undefined) => {
    if (!pattern || typeof pattern !== 'string') return ''
    
    // 常见模式的中文映射
    const patternMap: { [key: string]: string } = {
      'every_day': '每天',
      'every_week': '每周',
      'every_month': '每月',
      'every_year': '每年',
      'every_monday': '每周一',
      'every_tuesday': '每周二',
      'every_wednesday': '每周三',
      'every_thursday': '每周四',
      'every_friday': '每周五',
      'every_saturday': '每周六',
      'every_sunday': '每周日',
      'every_weekday': '每个工作日',
      'every_weekend': '每个周末',
      'every_2_days': '每两天',
      'every_3_days': '每三天',
      'every_week_on_monday': '每周一',
      'every_week_on_tuesday': '每周二',
      'every_week_on_wednesday': '每周三',
      'every_week_on_thursday': '每周四',
      'every_week_on_friday': '每周五',
      'every_week_on_saturday': '每周六',
      'every_week_on_sunday': '每周日',
      'every_2_weeks': '每两周',
      'every_month_on_1st': '每月1号',
      'every_month_on_15th': '每月15号',
      'every_month_last_day': '每月最后一天',
      'every_quarter': '每季度',
      'every_6_months': '每半年'
    }

    // 直接匹配
    if (patternMap[pattern]) {
      return patternMap[pattern]
    }

    // 动态解析常见格式
    if (pattern.startsWith('every_')) {
      // 处理 every_X_days 格式
      const daysMatch = pattern.match(/every_(\d+)_days?/)
      if (daysMatch) {
        return `每${daysMatch[1]}天`
      }

      // 处理 every_X_weeks 格式
      const weeksMatch = pattern.match(/every_(\d+)_weeks?/)
      if (weeksMatch) {
        return `每${weeksMatch[1]}周`
      }

      // 处理 every_X_months 格式
      const monthsMatch = pattern.match(/every_(\d+)_months?/)
      if (monthsMatch) {
        return `每${monthsMatch[1]}个月`
      }

      // 处理 every_X_years 格式
      const yearsMatch = pattern.match(/every_(\d+)_years?/)
      if (yearsMatch) {
        return `每${yearsMatch[1]}年`
      }
    }

    // 如果没有匹配到，返回原始值
    return pattern
  }

  // 获取最佳的重复描述（优先显示具体模式，否则显示类型）
  const getBestRecurringLabel = (type: string, pattern: string | null | undefined) => {
    if (pattern) {
      const patternLabel = getRecurringPatternLabel(pattern)
      // 如果模式比类型更具体，就显示模式
      const typeLabel = getRecurringTypeLabel(type)
      if (patternLabel && patternLabel !== typeLabel && patternLabel !== pattern) {
        return patternLabel
      }
    }
    return getRecurringTypeLabel(type)
  }

  const getPriorityColor = (priority: string) => {
    const colors = {
      P0: 'bg-red-100 text-red-700 border-red-200',
      P1: 'bg-orange-100 text-orange-700 border-orange-200',
      P2: 'bg-blue-100 text-blue-700 border-blue-200',
      P3: 'bg-theme-bg-tertiary text-theme-text-secondary border-theme-border'
    }
    return colors[priority as keyof typeof colors] || colors.P2
  }

  const getCategoryColor = (category: string) => {
    const colors = {
      work: 'bg-blue-100 text-blue-700',
      personal: 'bg-green-100 text-green-700',
      learning: 'bg-purple-100 text-purple-700',
      health: 'bg-pink-100 text-pink-700',
      other: 'bg-theme-bg-tertiary text-theme-text-secondary'
    }
    return colors[category as keyof typeof colors] || colors.other
  }

  if (isLoading) {
    return <LoadingSpinner size="lg" text="加载重复任务..." fullScreen />
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* Header */}
      <header className="sticky top-0 bg-theme-bg/95 backdrop-blur-sm shadow-sm border-b border-theme-border/60 z-10">
        <div className="flex items-center justify-between px-4 py-3 max-w-4xl mx-auto">
          <div className="flex items-center gap-3">
            <button
              onClick={() => navigate('/')}
              className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
            >
              <ArrowLeft size={20} />
            </button>
            <h1 className="text-lg font-semibold text-theme-text">重复任务管理</h1>
          </div>
          
          <div className="flex items-center gap-2">
            <button
              onClick={handleTriggerProcessing}
              className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
              title="手动处理重复任务"
            >
              <RefreshCw size={18} />
            </button>
            <button
              onClick={() => navigate('/create?recurring=true')}
              className="px-3 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-all shadow-sm"
            >
              <Plus size={16} className="inline mr-1" />
              新建重复任务
            </button>
          </div>
        </div>
      </header>

      <main className="px-4 pb-6 space-y-4 max-w-4xl mx-auto">
        {/* 统计概览 */}
        {stats && (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4">
            <div className="bg-theme-bg rounded-2xl p-4 border border-theme-border/60 shadow-sm">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-blue-50 rounded-xl border border-blue-100">
                  <Calendar size={20} className="text-blue-600" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-theme-text">{stats.totalRecurringTasks}</div>
                  <div className="text-sm text-theme-text-muted">总重复任务</div>
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-4 border border-theme-border/60 shadow-sm">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-green-50 rounded-xl border border-green-100">
                  <Play size={20} className="text-green-600" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-theme-text">{stats.activeRecurringTasks}</div>
                  <div className="text-sm text-theme-text-muted">活跃任务</div>
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-4 border border-theme-border/60 shadow-sm">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-purple-50 rounded-xl border border-purple-100">
                  <BarChart3 size={20} className="text-purple-600" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-theme-text">{stats.totalInstances}</div>
                  <div className="text-sm text-theme-text-muted">总实例数</div>
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-4 border border-theme-border/60 shadow-sm">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-orange-50 rounded-xl border border-orange-100">
                  <Clock size={20} className="text-orange-600" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-theme-text">{stats.upcomingInstances}</div>
                  <div className="text-sm text-theme-text-muted">待完成</div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 重复任务列表 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm">
          <div className="p-5 border-b border-theme-border/60">
            <div className="flex items-center gap-2">
              <div className="w-1 h-5 bg-gradient-to-b from-blue-500 to-blue-600 rounded-full"></div>
              <h2 className="text-sm font-semibold text-theme-text">重复任务列表</h2>
              <div className="ml-auto px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full font-semibold border border-blue-100">
                {recurringTasks ? recurringTasks.length : 0} 个
              </div>
            </div>
          </div>

          {!recurringTasks || recurringTasks.length === 0 ? (
            <div className="p-12 text-center">
              <Calendar size={48} className="mx-auto text-slate-300 mb-4" />
              <h3 className="text-lg font-medium text-theme-text mb-2">暂无重复任务</h3>
              <p className="text-theme-text-muted mb-6">创建重复任务来自动化您的日常工作</p>
              <button
                onClick={() => navigate('/create?recurring=true')}
                className="px-4 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-all"
              >
                创建第一个重复任务
              </button>
            </div>
          ) : (
            <div className="divide-y divide-theme-border/30">
              {recurringTasks && recurringTasks.map((task) => (
                <div key={task.id} className="p-6 hover:bg-theme-bg-secondary/50 transition-colors relative">
                  <div className="flex items-start gap-4">
                    {/* 状态指示器 */}
                    <div className="flex-shrink-0 mt-1.5">
                      {task.isActive ? (
                        <div className="w-3 h-3 bg-green-500 rounded-full shadow-sm border border-green-600/20"></div>
                      ) : (
                        <div className="w-3 h-3 bg-gray-400 rounded-full shadow-sm border border-gray-500/20"></div>
                      )}
                    </div>

                    {/* 任务信息 */}
                    <div className="flex-1 min-w-0">
                      <div className="mb-3">
                        <h3 className="font-medium text-theme-text mb-2">{task.title}</h3>
                        <div className="flex items-center gap-2">
                          <span className={`px-2 py-1 text-xs font-medium rounded-full border ${getPriorityColor(task.priority)}`}>
                            {task.priority}
                          </span>
                          <span className={`px-2 py-1 text-xs font-medium rounded-full ${getCategoryColor(task.category)}`}>
                            {task.category}
                          </span>
                        </div>
                      </div>

                      {task.description && (
                        <p className="text-sm text-theme-text-secondary mb-3 line-clamp-2">{task.description}</p>
                      )}

                      <div className="flex flex-wrap items-center gap-3 text-xs text-theme-text-muted mb-3">
                        <div className="flex items-center gap-1">
                          <Calendar size={12} />
                          <span>{getBestRecurringLabel(task.recurringType, task.recurringPattern)}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <BarChart3 size={12} />
                          <span>{task.instanceCount} 个实例</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Clock size={12} />
                          <span>{task.pendingCount} 个待完成</span>
                        </div>
                      </div>

                      {task.tags && task.tags.length > 0 && (
                        <div className="flex flex-wrap gap-1">
                          {task.tags.slice(0, 3).map((tag, index) => (
                            <span key={index} className="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full border border-blue-100">
                              {tag}
                            </span>
                          ))}
                          {task.tags && task.tags.length > 3 && (
                            <span className="px-2 py-1 bg-gray-50 text-gray-600 text-xs rounded-full border border-gray-200">
                              +{task.tags.length - 3}
                            </span>
                          )}
                        </div>
                      )}
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <button
                        onClick={() => handleToggleActive(task.id, task.isActive)}
                        className={`p-2 rounded-lg transition-all ${
                          task.isActive 
                            ? 'text-orange-600 hover:bg-orange-50 border border-orange-200' 
                            : 'text-green-600 hover:bg-green-50 border border-green-200'
                        }`}
                        title={task.isActive ? '暂停' : '恢复'}
                      >
                        {task.isActive ? <Pause size={14} /> : <Play size={14} />}
                      </button>

                      <button
                        onClick={() => handleGenerateInstances(task.id)}
                        className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all border border-blue-200"
                        title="生成实例"
                      >
                        <RefreshCw size={14} />
                      </button>

                      <div className="relative">
                        <button
                          onClick={() => setSelectedTask(selectedTask === task.id ? null : task.id)}
                          className="p-2 text-theme-text-secondary hover:bg-theme-bg-tertiary rounded-lg transition-all border border-theme-border/30"
                        >
                          <MoreHorizontal size={14} />
                        </button>

                        {selectedTask === task.id && (
                          <>
                            <div 
                              className="fixed inset-0 z-40" 
                              onClick={() => setSelectedTask(null)}
                            />
                            <div className="absolute right-0 top-full mt-2 w-48 bg-theme-bg rounded-lg border border-theme-border shadow-xl z-[60] backdrop-blur-sm">
                          <div className="py-1">
                            <button
                              onClick={() => {
                                navigate(`/recurring/${task.id}/edit`)
                                setSelectedTask(null)
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-theme-text-secondary hover:bg-theme-bg-secondary flex items-center gap-2"
                            >
                              <Edit3 size={14} />
                              编辑任务
                            </button>
                            <button
                              onClick={() => {
                                handleCopyTask(task)
                                setSelectedTask(null)
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-theme-text-secondary hover:bg-theme-bg-secondary flex items-center gap-2"
                            >
                              <Copy size={14} />
                              复制任务
                            </button>
                            <button
                              onClick={() => {
                                navigate(`/recurring/${task.id}/instances`)
                                setSelectedTask(null)
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-theme-text-secondary hover:bg-theme-bg-secondary flex items-center gap-2"
                            >
                              <BarChart3 size={14} />
                              查看实例
                            </button>
                            <div className="border-t border-theme-border/30 my-1"></div>
                            <button
                              onClick={() => {
                                handleDeleteTask(task.id, task.title)
                                setSelectedTask(null)
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50/50 flex items-center gap-2"
                            >
                              <Trash2 size={14} />
                              删除任务
                            </button>
                          </div>
                        </div>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </main>
    </div>
  )
}
